package com.greate.community.controller;

import com.greate.community.entity.DiscussPost;
import com.greate.community.entity.Page;
import com.greate.community.entity.User;
import com.greate.community.service.DiscussPostService;
import com.greate.community.service.LikeService;
import com.greate.community.service.RecommendService;
import com.greate.community.service.UserService;
import com.greate.community.util.CommunityConstant;
import com.greate.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页
 * @author 20721
 */
@Controller
public class IndexController implements CommunityConstant {

    @Resource
    private DiscussPostService discussPostService;

    @Resource
    private UserService userService;

    @Autowired
    private LikeService likeService;
    
    @Resource
    private RecommendService recommendService;

    @Autowired
    private HostHolder hostHolder;

    @GetMapping("/")
    public String root() {
        return "forward:/index";
    }

    /**
     * 进入首页
     * @param model
     * @param page
     * @param orderMode 默认是 0（最新）, 1（最热）, 2（推荐）
     * @return
     */
    @GetMapping("/index")
    public String getIndexPage(Model model, Page page, @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        // 获取当前登录用户
        User loginUser = hostHolder.getUser();
        int userId = loginUser != null ? loginUser.getId() : 0;
        
        // 基于推荐模式的不同处理逻辑
        if (orderMode == 2) {
            // 推荐模式
            page.setRows(discussPostService.findDiscussPostRows(0)); // 总行数仍然使用全部帖子数
            page.setPath("/index?orderMode=" + orderMode);
            
            // 获取推荐的帖子列表
            List<Map<String, Object>> discussPosts = recommendService.recommendPosts(
                    userId, page.getOffset(), page.getLimit());
            
            model.addAttribute("discussPosts", discussPosts);
        } else {
            // 最新或最热模式
            // 获取总页数
            page.setRows(discussPostService.findDiscussPostRows(0));
            page.setPath("/index?orderMode=" + orderMode);

            // 分页查询
            List<DiscussPost> list = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
            // 封装帖子和该帖子对应的用户信息
            List<Map<String, Object>> discussPosts = new ArrayList<>();
            if (list != null) {
                for (DiscussPost post : list) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("post", post);
                    User user = userService.findUserById(post.getUserId());
                    // 如果找不到用户，跳过该帖子
                    if (user == null) {
                        continue;
                    }
                    map.put("user", user);
                    long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                    map.put("likeCount", likeCount);

                    discussPosts.add(map);
                }
            }
            model.addAttribute("discussPosts", discussPosts);
        }
        
        model.addAttribute("orderMode", orderMode);
        return "index";
    }



    /**
     * 进入 500 错误界面
     * @return
     */
    @GetMapping("/error")
    public String getErrorPage() {
        return "/error/500";
    }

    /**
     * 没有权限访问时的错误界面（也是 404）
     * @return
     */
    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }

}
